/**
 * Created by kevin on 2017/7/7.
 */
/**
 * Created by kevin on 2017/6/2.
 */
var express = require('express');
var Users = require('../models/Users');
var router = express.Router();
var url = require("url");
var Robots = require('../models/Robots');
var Applications = require('../models/Applications');
var Packages = require('../models/Packages');
var ucheck = require('../utils/ucheck');
var multer  = require('multer');
var Delegater = require('../models/Delegaters');
var events = require('events');
var GitUsers = require('../models/GitUsers');
var pwdHash = require('../utils/pwd');
var Docs = require('../models/Docs');
var DocClassifies = require('../models/DocClassifies');
let webInfo = require('../utils/website');
var http = require('http');
var push = require('../utils/push');
let archiveTool = require('../utils/archive');
let pwdCode = require('../utils/pwd');
var Ding = require('../utils/dingding');

require('../utils/date');

var upload = multer({dest:'data/uploads/'});

let apiCodes = {
    999 : 'platform不正确',
    // 1000 ~ 1099 用户
    1001 : '请填写用户名',
    1002 : '请填写密码',
    1003 : '用户名或密码错误',
    1004 : '密码不正确',
    1005 : 'uid不能为空',
    1006 : '参数信息错误',
    1007 : '更新用户信息失败',
    1008 : '您无权进行此操作',
    1009 : '用户不存在',
    1010 : '登录信息失效',

    // 1100 ~ 1199
    1100 : '系统异常',
    1101 : 'app_id不能为空',
    1102 : 'delegate_id不能为空',
    1103 : 'package_id不能为空',
    1111 : '无法进行打包',

    1201 : '推送消息失败',
    200 : 'success'
};

function getCodeMessage(code) {
    return apiCodes[code];
}

function jsonResponse(code,data) {
    return {
        ec : code,
        em : getCodeMessage(code),
        result : (data ? data : {})
    };
}

function jsonResponseC(code,message,data) {
    return {
        ec : code,
        em : message,
        result : data
    }
}

// 用户
function formatUserInfo(user) {
    // let manage = platform === 'ios' ? user.role.permissions.managerI : user.role.permissions.managerA;
    return {
        nickname : user.nickname,
        username : user.username,
        role : user.role.name,
        email : user.email + '@' + webInfo.email(),
        avatar : webInfo.url() + '/images/avatar.png',
        authority : {
            ios_manage : user.role.permissions.managerI,
            android_manage : user.role.permissions.managerA,
            ios_package : user.role.permissions.packageI || user.role.permissions.managerI,
            android_package : user.role.permissions.packageA || user.role.permissions.managerA
        },
        uid : user._id
    };
}

router.post('/user/login',function (req,res) {
    let username = req.body.username;
    let passwd = req.body.passwd;
    // let platform = req.body.platform || 'ios';
    if (!username) {
        return res.json(jsonResponse(1001,null));
    }
    if (!passwd) {
        return res.json(jsonResponse(1002,null));
    }
    Users.getLoginInfo(username,function (err,user) {

        if (err || !user) {
            return res.json(jsonResponse(1003,null));
        }
        if (pwdHash(passwd) === user.passwd) {
            return res.json(jsonResponse(200,formatUserInfo(user)));
        } else {
            return res.json(jsonResponse(1004,null));
        }
    })
});

router.post('/user/detail',function (req,res) {
    // let platform = req.body.platform || 'ios';
    let uid = req.body.uid;
    if (!uid) {
        return res.json(jsonResponse(1005,null));
    }
    Users.getbyId(uid,function (err,user) {
        if (err || !user) {
            return res.json(jsonResponse(1009,null));
        } else {
            return res.json(jsonResponse(200,formatUserInfo(user)));
        }
    });
});

router.post('/user/update',function (req,res) {
    let uid = req.body.uid;
    let pwd = req.body.new_passwd;
    let oldPwd = req.body.old_passwd;
    let nickname = req.body.nickname;
    if (!pwd && !nickname) {
        return res.json(jsonResponse(1006,null));
    }
    function updateAction() {
        Users.edit(uid,doc,function (err) {
            if (err) {
                return res.json(jsonResponse(1007,null));
            } else {
                return res.json(jsonResponse(200,null));
            }
        });
    }
    var doc = {};
    pwd && (doc.passwd = pwd);
    nickname && (doc.nickname = nickname);
    if (pwd) {
        Users.getbyId(uid,function (err,user) {
            if (user && user.passwd === pwdCode(oldPwd)) {
                updateAction();
            } else {
                res.json(jsonResponse(1004,null));
            }
        })
    } else {
        updateAction();
    }

});

// 打包
router.post('/package/list',function (req,res) {
    // let platform = req.body.platform || 'ios';
    let id = req.body.app_id;
    let page = req.body.page;
    let pageSize = req.body.page_size;
    if (!id) {
        return res.json(jsonResponse(1101,null));
    }
    page = parseInt(page || 1);
    pageSize = parseInt(pageSize || 20);
    Packages.getPartByAppId(id,(page - 1) * pageSize,pageSize,function (err,list) {
        console.log(err);
        if (err) {
            return res.json(jsonResponse(1100,null));
        } else {
            var newList = [];
            for (p of list) {
                let info = {
                    id : p._id,
                    name : p.app.name,
                    icon :  webInfo.url() + p.app.iconUrl,
                    version : p.version,
                    build : p.build,
                    status : p.status,
                    url : p.dlurl,
                    package_user : p.user ? p.user.nickname : '未知用户',
                    package_time : p.ctime.getInterval()
                };
                newList.push(info);
            }
            return res.json(jsonResponse(200,newList));
        }
    });
});

router.post('/package/search',function (req,res) {
    // let platform = req.body.platform || 'ios';
    var num = parseInt(req.body.build);
    let id = req.body.app_id;
    if (!id) {
        return res.json(jsonResponse(1101,null));
    }
    Packages.getByAppAndBuild(id,num,function (err,list) {
        if (err) {
            return res.json(jsonResponse(200,null));
        } else {
            var newList = [];
            for (p of list) {
                let info = {
                    id : p._id,
                    name : p.app.name,
                    icon :  webInfo.url() + p.app.iconUrl,
                    version : p.version,
                    build : p.build,
                    url : p.dlurl,
                    status : p.status,
                    package_user : p.user.nickname,
                    package_time : p.ctime.getInterval()
                };
                newList.push(info);
            }
            return res.json(jsonResponse(200,newList));
        }
    });
});

// 文章
router.post('/docs/list',function (req,res) {
    DocClassifies.getAll(function (err,docClassifies) {
        if (err) {

        } else {
            function render(list) {
                if (readCount === total) {
                    res.json(jsonResponse(200,list));
                }
            };
            var readCount = 0;
            var total = docClassifies.length;

            var list = [];
            docClassifies.forEach(function (item) {
                Docs.getByClassifyAndLimit(item._id,10,function (err,docs) {
                    if (!err) {
                        var docList = [];
                        for (doc of docs) {
                            docList.push({
                                id : doc._id,
                                title : doc.name,
                                content : doc.content,
                                url : webInfo.url() + '/ueditor/doc?hide_nav=1&id=' + doc._id,
                                weight : doc.weight,
                                update_user : doc.updateUser ? doc.updateUser.nickname : '',
                                update_time : doc.utime.getInterval(),
                                update_time_desc : doc.updateTime
                            })
                        }
                        list.push({
                            title : item.name,
                            list : docList
                        });
                    }
                    readCount++;
                    render(list);
                });
            });

        }
    })
});

// 钉钉
router.get('/ding/text',function (req,res) {
    var token = req.query.token;
    var text = req.query.text;
    Ding.sendTextMessage(token,text);
    res.json(jsonResponse(200));
});

router.post('/*',function (req,res,next) {
    let platform = req.body.platform;
    if (platform !== 'ios' && platform !== 'android') {
        return res.json(jsonResponse(999,null));
    } else {
        next();
    }
});

router.post('/package/delegate',function (req,res) {
    let platform = req.body.platform || 'ios';
    let uid = req.body.uid;
    if (!uid) {
        return res.json(jsonResponse(1005,null));
    }
    Users.getbyId(uid,function (err,user) {
        if (err || !user) {
            return res.json(jsonResponse(1010,null));
        } else {
            let manage = platform === 'ios' ? user.role.permissions.managerI : user.role.permissions.managerA;
            let package =  manage || (platform === 'ios' ? user.role.permissions.packageI : user.role.permissions.packageA);

            if (!package) {
                return res.json(jsonResponse(1008,null));
            }
            Delegater.getListByType(platform === 'ios' ? 1 : 2,function (e,dList) {
                if (e) {
                    return res.json(jsonResponse(1100,null));
                } else {
                    var list = [];
                    var commendIndex = -1;
                    var commentValue = 10000;
                    var index = 0;
                    for (d of dList) {
                        if (d.packageSpend < commentValue) {
                            commentValue = d.packageSpend;
                            commendIndex = index;
                        }
                        list.push({
                            id : d._id,
                            name : d.name,
                            recommend : false,
                        });
                        index++;
                    }
                    if (commendIndex >= 0) {
                        list[commendIndex].recommend = true;
                    }
                    return res.json(jsonResponse(200,list));
                }
            });
        }
    });
});

router.post('/package/delete',function (req,res) {
    let platform = req.body.platform || 'ios';
    let uid = req.body.uid;
    let pid = req.body.package_id;
    if (!uid) {
        return res.json(jsonResponse(1005,null));
    }
    if (!pid) {
        return res.json(jsonResponse(1103,null));
    }
    let type = platform === 'ios' ? 1 : 2;
    Users.getbyId(uid,function (err,user) {
        if (err || !user) {
            return res.json(jsonResponse(1010, null));
        } else {
            let manage = platform === 'ios' ? user.role.permissions.managerI : user.role.permissions.managerA;
            let package = manage || (platform === 'ios' ? user.role.permissions.packageI : user.role.permissions.packageA);

            if (!package) {
                return res.json(jsonResponse(1008, null));
            }
            Packages.getById(pid,function (err,p) {
                if (p && p.type === type) {
                    Packages.remove({_id:pid},function (e) {
                        if (!e) {
                            return res.json(jsonResponse(200));
                        } else {
                            return res.json(jsonResponse(1100,null));
                        }
                    });
                } else {
                    return res.json(jsonResponse(1100,null));
                }
            })
        }
    });
});

router.post('/package/archive',function (req,res) {
    let platform = req.body.platform || 'ios';
    let uid = req.body.uid;
    let appId = req.body.app_id;
    let delegateId = req.body.delegate_id;
    if (!uid) {
        return res.json(jsonResponse(1005,null));
    }
    if (!appId) {
        return res.json(jsonResponse(1101,null));
    }
    if (!delegateId) {
        return res.json(jsonResponse(1102,null));
    }
    Users.getbyId(uid,function (err,user) {
        if (err || !user) {
            return res.json(jsonResponse(1010,null));
        } else {
            if (platform === 'ios') {
                let manage = user.role.permissions.managerI;
                let package =  manage || user.role.permissions.packageI;
                if (!package) {
                    return res.json(jsonResponse(1008,null));
                }
                archiveTool.archiveIOS(req,uid,appId,delegateId,req.session.socketServer,function (err,data) {
                    if (err) {
                        return res.json(jsonResponse(1111,null));
                    } else {
                        return res.json(jsonResponse(200));
                    }
                })
            } else {
                let manage = user.role.permissions.managerA;
                let package =  manage || user.role.permissions.packageA;
                if (!package) {
                    return res.json(jsonResponse(1008,null));
                }
                archiveTool.archiveAndroid(req,uid,appId,delegateId,req.session.socketServer,function (err,data) {
                    if (err) {
                        return res.json(jsonResponse(1111,null));
                    } else {
                        return res.json(jsonResponse(200));
                    }
                })
            }
        }
    });
});

// 列表

router.post('/app/list',function (req,res) {
    let platform = req.body.platform || 'ios';
    let type = null;
    if (platform === 'ios') {
        type = 1;
    } else if (platform === 'android') {
        type = 2;
    }
    Applications.getListByType(type,function (err,list) {
        if (err) {
            return res.json(jsonResponse(1100,null));
        } else {
            var newList = [];
            for (d of list) {
                let info = {
                    id : d._id,
                    name : d.name,
                    icon :  webInfo.url() + d.iconUrl,
                    version : d.version,
                    build : d.build,
                    status : d.status === 1 ? 1 : 0,
                    update_time : d.ptime ? d.ptime.getInterval() : d.ctime.getInterval()
                };
                newList.push(info);
            }
            return res.json(jsonResponse(200,newList));
        }
    });
});



router.get('/push/debug',function (req,res) {
    let platform = req.body.platform || 'ios';

    if (platform === 'ios') {
        push.pushIOS('测试消息',{type:1,id:'432423423423423423'},function (err,result) {
            if (err) {
                res.json(jsonResponseC(1201,err.message,{}));
            } else {
                res.json(jsonResponse(200,result));
            }
        });
    } else {
        push.pushIOS('测试消息标题','测试消息内容',{type:1,id:'432423423423423423'},function (err,result) {
            if (err) {
                res.json(jsonResponseC(1201,err.message,{}));
            } else {
                res.json(jsonResponse(200,result));
            }
        });
    }

});

module.exports = router;
